import matplotlib.pyplot as plt
import numpy as np

# 中文显示
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

def from_average_to_instantaneous():
    """演示从平均变化率到瞬时变化率的过程"""
    # 定义函数：f(x) = x^2
    f = lambda x: x**2
    x0 = 2
    
    # 不同的Δx值
    delta_x_values = [1.0, 0.5, 0.1, 0.01, 0.001]
    
    plt.figure(figsize=(12, 8))
    x_curve = np.linspace(0, 4, 1000)
    plt.plot(x_curve, f(x_curve), 'b-', linewidth=2, label='f(x) = x²')
    
    for i, dx in enumerate(delta_x_values):
        x1 = x0 + dx
        slope = (f(x1) - f(x0)) / dx
        
        # 绘制割线
        x_line = np.linspace(x0-0.5, x1+0.5, 100)
        y_line = f(x0) + slope * (x_line - x0)
        
        plt.plot(x_line, y_line, '--', alpha=0.7, 
                label=f'Δx={dx}, 斜率={slope:.3f}')
    
    plt.scatter([x0], [f(x0)], color='red', s=100, label=f'点({x0}, {f(x0)})')
    plt.title('从平均变化率到瞬时变化率（Δx → 0）')
    plt.xlabel('x'); plt.ylabel('f(x)')
    plt.legend(); plt.grid(True, alpha=0.3)
    plt.show()

from_average_to_instantaneous()